
class ItemModel
  _instance_count_ = 0

  constructor : ( list_model ) ->
    @list_model = list_model
    @text = new Notify( "Rah" + (_instance_count_++) )

  remove_item : () =>
    @list_model.remove_item( this )

class SimpleListModel
  constructor : () ->
    @items = new NotifyArray()
    @item_count = new Notify()
    @items.Subscribe( (n, o ) =>
      @item_count.SetValue( n.length )
    )

  add_item : () =>
    @items.add( new ItemModel( this ) )

  remove_item : (selected_item) =>
    @items.remove( selected_item )

  remove_all : () =>
    @items.clear()

  add_hundred : () =>
    values = @items.GetValue().slice(0)
    for i in [0...100]
      values.push( new ItemModel( this ))
    @items.reset( values )


template =
  o.Context( new SimpleListModel(),
    o.div(
      o.div(
        o.h3().text( (model) -> model.item_count )
      )
      o.a().attr( class : "button_example", href : "#" )
      .text("add an element")
      .event( "click", (list_model) -> list_model.add_item )

      o.a().attr( class : "button_example", href : "#" )
            .text("remove all")
            .event( "click", (list_model) -> list_model.remove_all )

      o.a().attr( class : "button_example", href : "#" )
           .text("add 100")
           .event( "click", (list_model) -> list_model.add_hundred )

      o.div(
        o.List( ((list_model) -> list_model.items),
          o.div(
            o.div().text((item) -> item.text )

            o.a().text("delete")
                 .attr( class : "button_example", href : "#")
                 .event( "click", (item) -> item.remove_item )

          ).enter_attr( class: "item" )
           .attr( class : "item item_update")
           .exit_attr( class: "item item_exit" )
        ).key_map( (item) -> item.text )
      )
    )
  )

template.write( document.getElementById("container") )
